<template>
    <div>
    	<Tabs value="user" @on-click="handleChangeTabs">
            <TabPane label="用户端" name="user"></TabPane>
            <TabPane label="商家端" name="partner"></TabPane>
        </Tabs>
        <SuperTable ref="table" path="/common/app/index" :params="params" :columns="columns">
            <Button slot="header-left" type="primary" @click="showModal = true">发布版本</Button>
            <div slot="header-right">
                <Form ref="filter" :model="filter" inline>
                    <FormItem label="所属平台" prop="platform">
                        <Select v-model="filter.platform" clearable style="width: 100px">
                            <Option value="android">android</Option>
                            <Option value="ios">ios</Option>
                        </Select>
                    </FormItem>
                    <Button type="primary" @click="handlFilter">筛选</Button>
                </Form>
            </div>
        </SuperTable>
        <Modal title="发布版本" v-model="showModal" :width="500" @on-cancel="handleCancel">
            <Form ref="form" :model="form" :rules="rules" :label-width="80">
                <FormItem label="平台" prop="platform">
                    <RadioGroup v-model="form.platform">
                        <Radio label="android"><Icon type="logo-android"></Icon><span>android</span></Radio>
                        <Radio label="ios"><Icon type="logo-apple"></Icon><span>ios</span></Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="版本号" prop="version">
                    <Input v-model="form.version" style="width: 260px;" placeholder="请填写版本号：1.0.0" />
                </FormItem>
                <FormItem v-if="form.platform == 'android'" label="下载地址" prop="download_url">
                    <div style="width: 260px;">
                        <Upload
                            ref="upload"
                            accept=".apk"
                            :action="ajax"
                            :headers="headers"
                            :default-file-list="defaultFileList"
                            :on-success="handleSuccess"
                            :before-upload="handleBeforeUpload"
                            :on-format-error="handleFormatError"
                        >
                            <Button icon="ios-cloud-upload-outline">上传Android安装包</Button>
                        </Upload>
                    </div>
                </FormItem>
                <FormItem v-else label="下载地址" prop="download_url">
                    <Input v-model="form.download_url" placeholder="请填写下载地址" />
                    <p style="margin-top: 8px; color: #999; line-height: 1;">IOS应用下载地址为APP Store下载地址，若没有变更开发者信息，无需修改</p>
                </FormItem>
                <FormItem label="强制更新" prop="is_force">
                    <RadioGroup v-model="form.is_force">
                        <Radio :label="0">否</Radio>
                        <Radio :label="1">是</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="版本描述" prop="desc">
	                <Input v-model="form.desc" :rows="8" maxlength="200" show-word-limit type="textarea" placeholder="请填写版本描述" />
	            </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancel">取消</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import SuperTable from '@/components/utils/super-table.vue';
import TableRows from '@/components/utils/table-rows.vue';
import { host } from '@/config/index.js';
import Cookies from 'js-cookie';

export default {
    components: {
        SuperTable,
        TableRows
    },
    data() {
        return {
        	ajax: host + '/attachmentApi/upload',
            headers: {},
            defaultFileList: [],
            submiting: false,
            showModal: false,
            form: {
                client: 'user',
                platform: 'android',
                version: '',
                download_url: '',
                is_force: 0,
                desc: ''
            },
            rules: {
                platform: [
                    {required: true,type: 'string', message: '请选择所属平台', trigger: 'change'}
                ],
                version: [
                    {required: true, message: '请填写版本号', trigger: 'blur'}
                ],
                download_url: [
                    {required: true, message: '请填写下载地址', trigger: 'blur'}
                ],
                is_force: [
                    {required: true,type: 'number', message: '请选择是否强制更新', trigger: 'change'}
                ],
            },
            filter: {
                platform: null,
            },
            params: {
            	client: 'user',
                page: 1,
                pageSize: 10
            },
            columns: [
                {
                    title: '所属平台',
                    key: 'platform'
                },
                {
                    title: '版本号',
                    key: 'version',
                    sortable: true,
                },
                {
                    title: '下载地址',
                    key: 'download_url'
                },
                {
                    title: '强制更新',
                    render: (h, params) => {
                        return h("span", {}, params.row.is_force ? '是' : '否');
                    }
                },
                {
                    title: '版本描述',
                    render: (h, params) => {
                        let content = params.row.desc
                        if (!content) return h('span', '');
                        content = content.length <= 50 ? content : content.substring(0, 50) + '...';
                        let Ptext = [
                            h('span',content)
                        ];
                        if (content.length > 50){
                            Ptext.push(
                                h("Poptip", {
                                    props:{
                                        transfer: true,
                                        width: '400',
                                        placement: 'right',
                                        trigger: 'hover',
                                        content: params.row.desc,
                                        wordWrap: true
                                    }
                                }, [
                                    h("a",'更多')
                                ])
                            )
                        }
                        return h('p', Ptext);
                    }
                },
                {
                    title: '发布时间',
                    key: 'created_at'
                },
                {
                    title: "操作",
                    align: "center",
                    key: "action",
                    width: 120,
                    render: (h, params) => {
                        return h("div", [
                            h("Button", {
                                style: {
                                    marginLeft: "5px"
                                },
                                props: {
                                    type: "error",
                                    size: "small"
                                },
                                on: {
                                    click: () => {
                                        this.handleDelete(params.row);
                                    }
                                }
                            }, "删除")
                        ])
                    }
                }
            ]
        }
    },
    mounted() {
        if(Cookies.get('token')) {
            this.headers.Authorization = 'Bearer ' + Cookies.get('token');
        }
    },
    methods: {
    	handleChangeTabs(client) {
    		this.params.client = client;
    		this.$refs.table.reload();
    		this.form.client = client;
    	},
    	handlFilter() {
            const { filter } = this;
            this.params.platform = filter.platform;
            this.$refs.table.init();
        },
        handleCancel() {
            this.showModal = false;
            setTimeout(() => {
                this.form.platform = 'android';
                this.form.version = '';
                this.form.download_url = '';
                this.form.is_force = 0;
                this.form.desc = '';
            }, 300)
        },
        handleSubmit() {
            if(this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    this.submiting = true;
                    this.$ajax.post('/common/app/save', this.form).then(res => {
                        this.$Message.success('添加成功');
                        this.submiting = false;
                        this.handleCancel();
                        this.$refs.table.init();
                    }).catch(err => {
                        this.submiting = false;
                        this.$Message.error(err.message || '提交失败');
                    })
                }
            })
        },
        handleDelete(row) {
            this.$Modal.confirm({
                title: "操作提示:",
                width: 320,
                content: `<p>您确定要删除版本‘${row.platform}${row.version}’吗?</p>`,
                onOk: () => {
                    const msg = this.$Message.loading({
                        content: '正在提交删除',
                        duration: 0
                    });
                    this.$ajax.delete('/common/app/delete', {params: {ids:[row.id]}}).then(() => {
                        msg();
                        this.$Message.success('操作成功');
                        this.$refs.table.reload();
                    }).catch(err => {
                        msg();
                        this.$Message.error(err.message || '操作失败');
                    })
                }
            });
        },
        //上传版本
        handleSuccess (res, file, fileList) {
            this.form.download_url = res.data.full_url;
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: file.name + ' 的格式不正确， 请选择APK格式的文件。'
            });
        },
        handleBeforeUpload () {
            this.$refs.upload.clearFiles();
            return true;
        }
    }
}
</script>